package streamLogStaticJava.utils;

import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @ClassName CodeStr
 * @Description 使用jdk加密算法对数据加密
 * @Author dalong
 * @Date 2020/6/28 18:36
 * @Version 1.0
 **/

public class CodeStr {

    /**使用指定算法类型进行加密
     * MD5
     * SHA-1
     * SHA-256
     * ---------
     * HASH  自定义取hashcode
     * */
    public  String EncoderStr(String str,String code) throws NoSuchAlgorithmException, UnsupportedEncodingException {

        String codeStr;
        switch (code){
            case "HASH":{
                 codeStr = String.valueOf(str.hashCode());
                break;
            }default:{
                MessageDigest md5 = MessageDigest.getInstance(code);
                BASE64Encoder base64Encoder = new BASE64Encoder();

                codeStr = base64Encoder.encode(md5.digest(str.getBytes("UTF-8")));
            }
        }

        return codeStr;
    }

    /**
     * 默认使用MD5方式
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public  String EncoderStr(String str) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return EncoderStr(str,"MD5");
    }
}
